<?php

namespace plugin\admin\app\controller;

use plugin\admin\app\common\Util;
use plugin\admin\app\constant\v1\CommonConstant;
use support\Request;
use support\Response;
use plugin\admin\app\model\V1UserMoneyLog;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;

/**
 * 业绩列表
 */
class V1UserMoneyListController extends Crud
{
    /**
     * 无需登录及鉴权的方法
     * @var array
     */
    protected $noNeedLogin = [];

    /**
     * 需要登录无需鉴权的方法
     * @var array
     */
    protected $noNeedAuth = [
        'select'
    ];
    
    /**
     * @var V1UserMoneyLog
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new V1UserMoneyLog;
    }
    
    /**
     * 浏览
     * @return Response
     */
    public function index(): Response
    {
        return view('v1-user-money-list/index');
    }

    /**
     * 查询
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function select(Request $request): Response
    {
        $created_at = $request->input('created_at');
        if(!$created_at){
            return json(['code' => 0, 'msg' => '暂无数据', 'count'=>0,'data' => []]);
        }

        $start = $created_at[0].' 00:00:00';
        $end = $created_at[1].' 23:59:59';
        $admin = admin();
        $db = Util::db();

        // 查询消费金额
        $consumptionQuery = $db->table('wa_v1_user_money_log')
            ->where('deleted', CommonConstant::DELETE_0)
            ->whereIn('type',[CommonConstant::MONEY_LOG_TYPE_4,CommonConstant::MONEY_LOG_TYPE_5,CommonConstant::MONEY_LOG_TYPE_6,CommonConstant::MONEY_LOG_TYPE_10])
            ->where('money','>',0)
            ->whereBetween('created_at', [$start, $end])
            ->when('user_id', function ($query) use ($admin) {
                if($admin['user_status'] == CommonConstant::DEFAULT_2){
                    return $query->where('user_id', $admin['id']);
                }
            })
            ->selectRaw("DATE_FORMAT(created_at, '%Y-%m') as month, line_id,
            SUM(CASE WHEN type IN ('node_buy', 'node_renew', 'node_average_time') THEN money ELSE 0 END) as total_income,
            SUM(CASE WHEN type = 'node_refund' THEN money ELSE 0 END) as total_refund,
            (SUM(CASE WHEN type IN ('node_buy', 'node_renew', 'node_average_time') THEN money ELSE 0 END) - 
             SUM(CASE WHEN type = 'node_refund' THEN money ELSE 0 END)) as consumption")
            ->groupBy('month', 'line_id');

        // 查询提成金额
        $commissionQuery = $db->table('wa_v1_user_commission_log')
            ->where('deleted', CommonConstant::DELETE_0)
            ->whereIn('type',[CommonConstant::MONEY_LOG_TYPE_4,CommonConstant::MONEY_LOG_TYPE_5,CommonConstant::MONEY_LOG_TYPE_10])
            ->whereBetween('created_at', [$start, $end])
            ->when('user_id', function ($query) use ($admin) {
                if($admin['user_status'] == CommonConstant::DEFAULT_2){
                    return $query->where('user_id', $admin['id']);
                }
            })
            ->selectRaw("DATE_FORMAT(created_at, '%Y-%m') as month, line_id,
                SUM(CASE WHEN type IN ('node_buy', 'node_renew') THEN money ELSE 0 END) as total_commission,
                SUM(CASE WHEN type = 'node_refund' THEN money ELSE 0 END) as total_refund,
                (SUM(CASE WHEN type IN ('node_buy', 'node_renew') THEN money ELSE 0 END) - 
                 SUM(CASE WHEN type = 'node_refund' THEN money ELSE 0 END)) as commission")
            ->groupBy('month', 'line_id');

        // 获取结果
        $consumptionResults = $consumptionQuery->get();
        $commissionResults = $commissionQuery->get();

        // 合并两个结果集
        $results = [];

        // 处理消费结果
        foreach ($consumptionResults as $item) {
            $key = $item->month . '-' . $item->line_id;
            $results[$key] = [
                'month' => $item->month,
                'line_id' => $item->line_id,
                'consumption' => (float)$item->consumption,
                'commission' => 0
            ];
        }

        // 处理佣金结果
        foreach ($commissionResults as $item) {
            $key = $item->month . '-' . $item->line_id;
            if (isset($results[$key])) {
                $results[$key]['commission'] = (float)$item->commission;
            } else {
                $results[$key] = [
                    'month' => $item->month,
                    'line_id' => $item->line_id,
                    'consumption' => 0,
                    'commission' => (float)$item->commission
                ];
            }
        }

        $lineColumn = $db->table('wa_v1_line')
            ->where('deleted', CommonConstant::DELETE_0)
            ->pluck('name','id')
            ->toArray();

        // 添加线路名称并转换为数组
        $items = [];
        foreach ($results as $item) {
            $item['line_name'] = $lineColumn[$item['line_id']] ?? '未知分类';
            $items[] = $item;
        }

        return json(['code' => 0, 'msg' => 'ok', 'count'=>0,'data' => $items]);
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::insert($request);
        }
        return view('v1-user-money-list/insert');
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
    */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::update($request);
        }
        return view('v1-user-money-list/update');
    }

}
